<?php

namespace app\api\controller\pifa;

use app\common\controller\Api;
use think\Config;
use think\Db;
use think\Validate;
use think\Session;
use fast\WechatMini;
use fast\Feiyong;
use addons\third\model\Third;
use think\Log;
use think\Request;
use fast\Http;
use think\Exception;
use addons\third\library\Service;
use app\api\model\Goodsitem;
use addons\epay\library\Service as PayService;
use app\api\library\Order as PayOrder;
use fast\Tongbu;
use addons\litestore\model\Litestorefreight;
use addons\litestore\model\Wxlitestoregoods;

use fast\AdapayUtil;
use fast\Saobei;


class Orderxiaoshou extends Api
{

    protected $noNeedLogin = ['login','getconfig','getMendian1','token','getfenlei'];
    protected $noNeedRight = ['*'];

     //销售订单

    public function xiaoshouorderlist()
    {
        $post = $this->request->request();

        $Order = new \app\admin\model\pifa\Order;
        $map['fa_pifa_order.inv_id'] = $this->auth->id;
        $map['fa_pifa_order.kehu_id'] = ['<>',0];

        if ($post['orderstate'] != '-1') {
            $map['fa_pifa_order.paystate'] = $post['orderstate'];
        }
        $list = $Order
                   
                    ->where($map)
                    ->order('createtime desc')
                    ->paginate(12);
        

        $list = $list->toArray();

        $OrderitemModel = new \app\admin\model\pifa\Orderitem;

        foreach ($list['data'] as $key => $value) {
            $list['data'][$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
            $map2['order_id'] = $value['id'];
            $item = $OrderitemModel::with(['goods'])->where($map2)->select();
            $list['data'][$key]['item'] = $item;
        }

      

        $this->success("成功",$list);
    } 

    public function pre()
    {
        $post = file_get_contents( "php://input");
        $post = json_decode($post,true);
        $ids = [];
        $num = 0;
        $price = 0;
        $price2 = 0;
        $baojia_price_total = 0;

        if (isset($post['is_youhui']) &&  !empty($post['is_youhui'])) {
            $is_youhui = $post['is_youhui'];
        }else{
            $is_youhui = 0;
        }

        $result['yunfei'] = 0;



        $map2['user_id'] = $post['kehu_id'];
        $map2['status'] = '1';
        $user_vip = Db::table('fa_pifa_md')->where($map2)->find();


        $user = Db::table('fa_user')->find($post['kehu_id']);
        $baojia_id = 0;
        if (!empty($user['baojia_id'])) {
            $baojia_id = $user['baojia_id'];
        }

     

        foreach ($post['goods_list'] as $key => $value) {
            $map['fa_litestore_goods_spec.goods_id'] = $value['goods_id'];
            $map['fa_litestore_goods_spec.goods_spec_id'] = $value['sku_price_id'];
            $res = Goodsitem::with(['goods'])->where($map)->find();

            if (empty($res)) {
                unset($post['goods_list'][$key]);
                continue;

            }

            $baojia_price = 0;
            if (!empty($baojia_id) && !empty($res['baojia'])) {
                $baojia = json_decode($res['baojia'],true);

                if (isset($baojia[$baojia_id])) {
                    $res['goods_price'] = bcadd($baojia[$baojia_id], $res['goods_price'], 2);
                    $res['goods_price2'] = bcadd($baojia[$baojia_id], $res['goods_price2'], 2);
                }

            }



              // 会员价 & 原价
            $original_price = bcmul($res['goods_price'], $value['goods_num'], 2);
            $vip_price = bcmul($res['goods_price2'], $value['goods_num'], 2);

            
             // 默认价格（根据会员身份选择）
            $final_price = $user_vip ? $vip_price : $original_price;

            $res = $res->toArray();
            $post['goods_list'][$key]['info'] = $res;
            if ($user_vip) {
                $post['goods_list'][$key]['goods_price'] = $res['goods_price2'];
            }else{
                $post['goods_list'][$key]['goods_price'] = $res['goods_price'];
            }



            $num = $num + $value['goods_num'];
            $post['goods_list'][$key]['price'] = bcmul($res['goods_price'],$value['goods_num'],2);
            $post['goods_list'][$key]['price2'] = bcmul($res['goods_price2'],$value['goods_num'],2);
            $price = bcadd($price,$post['goods_list'][$key]['price'],2);
            $price2 = bcadd($price2,$post['goods_list'][$key]['price2'],2);
            $baojia_price_total = bcadd($baojia_price_total,$baojia_price,2);
           

            $goods_total_weight = bcmul($res['goods_weight'], $value['goods_num'], 2);
            $Litestorefreight = Litestorefreight::with('rule')->find($res['goods']['delivery_id']);
            // $expressPrice = $Litestorefreight->calcTotalFee($value['goods_num'], $goods_total_weight, 1);
            

          
             $post['goods_list'][$key]['final_price'] = $final_price;


            // $total_price = bcadd($total_price, $final_price, 2);



            // $result['yunfei'] = $result['yunfei']+$expressPrice;
       
           


        }   
        $site = Config::get("site");
     
        $result['yunfei'] = $site['yunfei'];




        $zhekou = 0;
        $jisuan_youhui_price = $price;


        


        if (!empty($user_vip)) {
            $zhekou = bcsub($price,$price2,2);
            $jisuan_youhui_price = $price2;
        }

        if ($jisuan_youhui_price  >= $site['mianpeisong']) {
            $result['yunfei'] = 0;
        }



        $post['goods_list'] = array_values($post['goods_list']);

        $result['new_goods_list'] = $post['goods_list'];
        $result['now_price'] = $jisuan_youhui_price+$result['yunfei'];
        $result['goods_num'] = $num;
        $result['goods_price'] = $price;
        $result['zhekou'] = $zhekou;

        if ($is_youhui == 1) {
            $Useryouhuijuan = new \app\admin\model\pifa\Useryouhuijuan;

            $map3['user_id'] = $this->auth->id;
            $map3['fa_pifa_useryouhuijuan.status'] = '0';
            $map3['fa_pifa_useryouhuijuan.end_time'] = ['>',time()];
            $youhuijuan = $Useryouhuijuan->with(['youhuijuan'])->where($map3)->order('createtime desc')->select();
           
            $result['youhui_use'] = [];
            $result['youhui_not_user'] = [];
            $a = 0;
            $b = 0;
            foreach ($youhuijuan as $key => $value) {

                if ($value['youhuijuan']['min_price'] <= $jisuan_youhui_price) { 
                    $result['youhui_use'][$a] = $value;
                    $a++;
                }else{
                    $result['youhui_not_user'][$b] = $value;
                    $b++;
                }
            }
      
        }

        $this->success("成功",$result);
    }

    public function orderDetail()
    {
        $post = $this->request->request();

        $Order = new \app\admin\model\pifa\Order;
        $info = $Order::with(['address2'])->find($post['id']);

        $info = $info->toArray();

        $map['order_id'] = $post['id'];
        $OrderitemModel = new \app\admin\model\pifa\Orderitem;

        $list = $OrderitemModel::with(['goods'])->where($map)->select();
     

        $info['item'] =  $list;

        $shangjia = Db::table('fa_pifa_shangjia')->find($info['mendian_id']);

        

        $info['createtime'] = date('Y-m-d H:i:s',$info['createtime']);
        $info['freight_time'] = date('Y-m-d H:i:s',$info['freight_time']);
        $info['shangjia'] = $shangjia;
        $map_peisong_desc['order_id'] = $info['id'];
        $info['peisong_desc'] = Db::table('fa_pifa_orderdesc')->where($map)->select();

        foreach ($info['peisong_desc'] as $key => $value) {
           $value['images'] = explode(',',$value['images']);

           foreach ($value['images'] as $key1 => $value1) {
               $value['images'][$key1] = $this->request->root(true).$value1;
           }

           $info['peisong_desc'][$key]['images'] = $value['images'];

           
           $info['peisong_desc'][$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
        }


        if (!empty($info['peisong_user_id'])) {
            $info['peisong'] = Db::table('fa_user')->field('nickname,mobile,avatar')->find($info['peisong_user_id']);
        }

        $this->success("成功",$info);


    }

    public function createOrder()
    {
        $post = file_get_contents( "php://input");
        $post = json_decode($post,true);
        $ids = [];
        $num = [];
        $price = 0;
        $price2 = 0;

        $map3['id'] = $post['kehu_id'];
        $kehu = Db::table('fa_pifa_kehu')->where($map3)->find();
         if (empty($kehu)) {
           $this->error('客户不存在');
        }

        if (empty($post['mendian_id'])) {
           $this->error('门店不存在');
        }
       

        $cat_id = [];
        $user = Db::table('fa_user')->find($kehu['user_id']);

        $youhui_id = $post['youhui_id'];

        
        $yunfei = 0;
        $fenyong = 0;
        $goods_price = 0;
        $goods_price3 = 0;
        $goods_price4 = 0;
        $qudaofenyong = 0;
        $baojia_id = 0;
        if (!empty($user['baojia_id'])) {
            $baojia_id = $user['baojia_id'];
        }


        foreach ($post['goods_list'] as $key => $value) {
          

            $map['fa_litestore_goods_spec.goods_id'] = $value['goods_id'];
            $map['fa_litestore_goods_spec.goods_spec_id'] = $value['sku_price_id'];

            array_push($cat_id,$value['sku_price_id']);
            $res = Goodsitem::with(['goods'])->where($map)->find();
            if (empty($res)) {
                unset($post['goods_list'][$key]);
                continue;

            }
            $res = $res->toArray();
            $post['goods_list'][$key]['info'] = $res;


            $baojia_price = 0;
            if (!empty($baojia_id) && !empty($res['baojia'])) {
                $baojia = json_decode($res['baojia'],true);

                if (isset($baojia[$baojia_id])) {
                    $res['goods_price'] = bcadd($baojia[$baojia_id], $res['goods_price'], 2);
                    $res['goods_price2'] = bcadd($baojia[$baojia_id], $res['goods_price2'], 2);
                }

            }

            
            $post['goods_list'][$key]['price'] = bcmul($res['goods_price'],$value['goods_num'],2);
            $post['goods_list'][$key]['price2'] = bcmul($res['goods_price2'],$value['goods_num'],2);

            

        
            $post['goods_list'][$key]['fenyong'] = bcmul($res['fenyong'],$value['goods_num'],2);
            $post['goods_list'][$key]['qudao_fenyong'] = bcmul($res['qudao_fenyong'],$value['goods_num'],2);
            $post['goods_list'][$key]['goods_price3'] = bcmul($res['goods_price3'],$value['goods_num'],2);
            $post['goods_list'][$key]['goods_price4'] = bcmul($res['goods_price4'],$value['goods_num'],2);

            $goods_price3 = bcadd($post['goods_list'][$key]['goods_price3'],$goods_price3,2);
            $goods_price4 = bcadd($post['goods_list'][$key]['goods_price4'],$goods_price4,2);
            $fenyong = bcadd($post['goods_list'][$key]['fenyong'],$fenyong,2);
            $qudaofenyong = bcadd($post['goods_list'][$key]['qudao_fenyong'],$qudaofenyong,2);
            


            $price = bcadd($price,$post['goods_list'][$key]['price'],2);
            $price2 = bcadd($price2,$post['goods_list'][$key]['price2'],2);

            $goods_total_weight = bcmul($res['goods_weight'], $value['goods_num'], 2);
            $Litestorefreight = Litestorefreight::with('rule')->find($res['goods']['delivery_id']);
            $expressPrice = $Litestorefreight->calcTotalFee($value['goods_num'], $goods_total_weight, 1);

            // $yunfei = $yunfei+$expressPrice;


        }   

        $post['goods_list'] = array_values($post['goods_list']);
        $new_goods_list = $post['goods_list'];


       
        $insdata['order_no'] = 'QF'.date('YmdHis') . $this->auth->id;
     
        


        $map2['user_id'] = $kehu['user_id'];
        $map2['status'] = '1';
        $user_vip = Db::table('fa_pifa_md')->where($map2)->find();
        $zhekou = 0;
        
      

        $jisuan_youhui_price = $price;
        if (!empty($user_vip)) {
            $zhekou = bcsub($price,$price2,2);
            $jisuan_youhui_price = $price2;
        }



        $store = Db::table('fa_pifa_shangjia')->field('*, ' . getDistanceBuilder($kehu['lat'], $kehu['lng']))->where('id','=',$post['mendian_id'])->find();


        if (!isset($store['distance']) || $store['distance'] > $store['service_radius']) {

       
            $this->error('不在该地区销售');

        }
        
        
        $site = Config::get("site");

        $yunfei= $site['yunfei'];
        if ($jisuan_youhui_price < $site['qisong']) {
           $this->error('注意:需要满'.$site['qisong'].'元起送!');

           return;
        }
        
        
        if ($jisuan_youhui_price  >= $site['mianpeisong']) {
            $yunfei = 0;
        }
     
        

        $youhui = [];
        if (!empty($youhui_id)) {
            $Useryouhuijuan = new \app\admin\model\pifa\Useryouhuijuan;
            $youhui = $Useryouhuijuan
                    ->with(['youhuijuan'])->find($youhui_id);

            if (empty($youhui)) {
                $this->error('优惠卷不存在');
            }
            if ($youhui['user_id'] != $this->auth->id) {
                $this->error('优惠卷异常');
            }

            if ($youhui['end_time'] <= time()) {
                $this->error('优惠卷已过期');
            }
            if ($youhui['status'] != '0') {
                $this->error('优惠卷已失效');
            }

            if ($jisuan_youhui_price < $youhui['youhuijuan']['min_price']) {
                $this->error('商品需大于'.$youhui['youhuijuan']['min_price'].'才能使用优惠卷');
            }
        }
     
        Db::startTrans();
        try {

            $insdata['user_id'] = $kehu['user_id'];

            $insdata['inv_id'] = $this->auth->id;
            if (!empty($insdata['inv_id'])) {
                $insdata['inv_id'] = $insdata['inv_id'];
                $mapdaili['user_id'] = $insdata['inv_id'];
                $mapdaili['status'] = '1';
                $restuiguang = Db::table('fa_pifa_tuiguangyuan')->where($mapdaili)->find();
                if (!empty($restuiguang)) {
                    $insdata['fen_price'] = $fenyong;
                }
                $resdali = Db::table('fa_pifa_daili')->where($mapdaili)->find();
                if (!empty($resdali)) {
                    $insdata['fen_price'] = $qudaofenyong;
                    $insdata['fen_type'] = 1;
                }
            }
            
            $insdata['mendian_id'] = $post['mendian_id'];
            $insdata['kehu_id'] = $post['kehu_id'];
            $insdata['consignee'] = $kehu['consignee'];
            $insdata['phone'] = $kehu['phone'];
            $insdata['address'] = $kehu['address'].$kehu['xiangxi'];
            $insdata['province_id'] = $kehu['province_id'];
            $insdata['city_id'] = $kehu['city_id'];
            $insdata['area_id'] = $kehu['area_id'];
            $insdata['lat'] = $kehu['lat'];
            $insdata['lng'] = $kehu['lng'];
            $insdata['goods_price'] = $jisuan_youhui_price;
            $insdata['chengben'] = $goods_price4;
            $insdata['price'] = $jisuan_youhui_price+$yunfei;
            $insdata['yunfei'] = $yunfei;
            $insdata['zhekou'] = $zhekou;

            $insdata['emo'] = $post['remark'];
            $insdata['peisong_time'] = $post['peisong_time'];
            $insdata['mendian_id'] = $post['mendian_id'];
            $insdata['createtime'] = time();
            $insdata['createday'] = date('Y-m-d');
            $insdata['createmonth'] = date('Y-m');
            $insdata['updatetime'] = time();
            $insdata['orderstate'] = '0';
            $insdata['expiretime'] = time()+(60*60*24*3);

            if (!empty($youhui)) {
                $insdata['youhui'] = $youhui['youhuijuan']['price'];
                $insdata['price'] = $insdata['price'] - $youhui['youhuijuan']['price'];
            }


            $res = Db::table('fa_pifa_order')->insertGetId($insdata);

            foreach ($new_goods_list as $key => $value) {

              
                $ins = [];
                $ins['order_id'] = $res;
                $ins['user_id'] = $this->auth->id;
                $ins['goods_id'] = $value['goods_id'];
                $ins['shangjia_id'] = $post['mendian_id'];
                $ins['gongyingshang_id'] = $value['info']['goods']['gongyingshang_id'];
                $ins['goods_name'] = $value['info']['goods']['goods_name'];
                $ins['image'] = $value['info']['goods']['image'];
                $ins['goods_item_id'] = $value['info']['goods_spec_id'];
                $ins['name'] = $value['info']['spec_name'];
                $ins['goods_no'] = $value['info']['goods_no'];
                $ins['goods_num'] = $value['goods_num'];
                $ins['goods_price3'] = $value['goods_price3'];
                $ins['goods_price4'] = $value['goods_price4'];
                $ins['createtime'] = time();
                $ins['updatetime'] = time();
                $ins['price'] = $value['price'];
                if (!empty($user_vip)) {
                      $ins['price'] = $value['price2'];
                }
                $ins['shanghu_price'] = bcsub($ins['price'],$value['goods_price3'],2);
                Db::table('fa_pifa_orderitem')->insert($ins);
            }

            if (isset($post['from']) && $post['from'] == 'cart') {
            
                $map_car['user_id'] = $this->auth->id;
                $map_car['goods_item_id'] = ['IN',$cat_id];
                Db::table('fa_pifa_cart')->where($map_car)->delete();
            }

            if (!empty($youhui_id)) {
              
                $map_my['id'] = $youhui_id;
                $updata_my['status'] = '1';
                Db::table('fa_pifa_useryouhuijuan')->where($map_my)->update($updata_my);
            }

            Db::commit();
            $this->success("成功",$res);
        } catch (Exception $e) {
             Db::rollback();
            //出错回滚
             $this->error($e->getMessage());
            Log::error($e);
            $this->error(__('下单失败'));

        }

        
    }
 


}